<template>
  <basic-container>
     <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :search.sync="search"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
       <!--自定义菜单-->
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" plain v-if="permission.drawingnumberapplication_add" @click="handleAdd">新 增</el-button>
          <!-- <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.drawingnumberapplication_delete" @click="handleDelete">删 除</el-button> -->
          <el-button type="warning" size="small" icon="el-icon-download" plain @click="exportExcel">导 出</el-button>
        </template>
       <!--产品大类-->
       <template slot-scope="{row}"
                 slot="productChildId">
         {{row.productChildIdName}}
       </template>
       <!--自定义菜单栏-->
       <template  slot="menu" slot-scope="scope">
         <el-button icon="el-icon-view" size="small" type="text" @click="viewBtnFun(scope.row)">查 看</el-button>
       </template>
      </avue-crud>

     <!--图号申请模态窗口-->
    <div v-if="addBox">
      <el-dialog title="图号申请" :visible.sync="addBox" width="60%" append-to-body>
        <avue-form ref="form" v-model="formApplication" :option="formOption" @submit="addDrawingApplication">
          <template slot-scope="scope" slot="menuForm">
            <el-button @click="addBox = false" size="small" icon="el-icon-close">取 消</el-button>
          </template>
        </avue-form>
      </el-dialog>
    </div>

    <!--查看图号的申请详情-->
    <div v-if="viewBox">
      <el-dialog title="图号查看" :visible.sync="viewBox" width="55%" append-to-body>
        <el-table
          :data="tableData"
          border
          height="400"
          size="medium"
          style="width: 100%">
          <el-table-column align="center" prop="productParentIdName" label="产品父类" width="200px"></el-table-column>
          <el-table-column align="center" prop="productChildIdName" label="产品大类"></el-table-column>
          <el-table-column prop="drawingCategoryName" align="center" label="图纸类别"></el-table-column>
          <el-table-column prop="number" align="center" label="图号"></el-table-column>
          <el-table-column prop="userAccount" align="center" label="申领人"></el-table-column>
          <el-table-column prop="status" align="center" label="状态"></el-table-column>
        </el-table>
      </el-dialog>
    </div>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, getLoginUserInfo, getApplicationDetailList} from "@/api/drawing/drawingnumberapplication";
  import {mapGetters} from "vuex";
  import {getToken} from '@/util/auth';
  import {getDictionary} from '@/api/system/dict';
  import {findByvalue} from '@/util/util';

  export default {
    data() {
      let validateNum = (rule,value,callback) => {
        // 验证的正则表达式
        let reg = /^[0-9]+\.?[0-9]*$/;
        if (!reg.test(value)) {
          callback(new Error('请输入数字格式'));
        } else {
          callback();
        }
      };
      return {
        // 图号查看编辑
        tableData:[],
        // 查看图号申请的详情
        viewBox:false,
        // 搜索信息
        search:{},
        // 图号申请模态
        addBox:false,
        // 表单申请
        formApplication:{},
        formOption:{
          // 清空按钮
          emptyBtn:false,
          column:[
            {
              label:'申请人',
              prop: "userAccount",
              span:8,
              disabled:true,
            },
            {
              label: '申请部门',
              prop:'deptName',
              span: 8,
              disabled: true
            },
            {
              label: '申领时间',
              type: "datetime",
              prop: 'applicationTime',
              disabled: true,
              span: 8,
            },
            {
              label: '产品父类',
              type: 'select',
              prop: "productParentId",
              span: 8,
              props:{
                label:'name',
                value:'id'
              },
              rules: [{
                message: "选择产品父类",
                required: true,
                trigger: 'blur'
              }],
              dicUrl:`/api/data-drawing-number-application/drawingnumberapplication/getEquipmentCategoryParentNode`,
              cascaderItem:['productChildId'],
            },
            {
              label: '产品大类',
              prop: 'productChildId',
              type: 'select',
              span: 8,
              cascaderIndex:0,
              props:{
                label:'name',
                value:'id'
              },
              rules: [{
                message: "选择产品大类",
                required: true,
                trigger: 'blur'
              }],
              dicUrl: `/api/data-drawing-number-application/drawingnumberapplication/getChildNodeByParentId?parentId={{productParentId}}`,
            },
            {
              label: '图纸类别',
              type: 'tree',
              prop: 'drawingCategory',
              span: 8,
              props: {
                label: "name",
                value: "id"
              },
              dicUrl: "/api/data-category/drawingcategory/getDrawingCateGoryList",
              rules: [{
                message:'请选择图纸类别',
                required: true,
                trigger: 'blur'
              }]
            },
            {
              label: '申请数量',
              prop: 'num',
              span: 8,
              rules: [{
                message: "请输入申请数量",
                required: true,
                trigger: "blur",
                validator:validateNum,
              }]
            },
            {
              label: '备注',
              prop: "remark",
              span: 16,
            },
          ],
        },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          // 禁用新增按钮
          addBtn: false,
          // 禁用查看按钮
          viewBtn: false,
          delBtn: false,
          editBtn: false,
          height:'auto',
          calcHeight: 'auto',
          tip: false,
          searchShow: true,
          border: true,
          index: true,
          indexLabel:'序号',
          selection: true,
          dialogClickModal: false,
          align:'center',
          menuAlign:'center',
          column: [
            {
              label: '申请部门',
              prop:'deptName',
              editDisabled:true,
              span:8,
            },
            {
              label:'申请人',
              prop: "userAccount",
              editDisabled:true,
              span: 8,
              width: 100,
            },
            {
              label: '申领时间',
              prop: 'applicationTime',
              width: 140,
              editDisabled:true,
              span: 8,
              type: "datetime",
              search:true,
              // 按照时间范围来查询
              searchRange:true,
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
            },
            {
              label: "产品父类",
              prop: "productParentId",
              width:155,
              type:'select',
              search: true,
              cascaderIndex:0,
              span: 8,
              props:{
                label:'name',
                value:'id'
              },
              rules: [{
                message: "选择产品父类",
                required: true,
                trigger: 'blur'
              }],
              dicUrl:`/api/data-drawing-number-application/drawingnumberapplication/getEquipmentCategoryParentNode`,
              cascaderItem:['productChildId'],
            },
            {
              label: '产品大类',
              prop: 'productChildId',
              span: 8,
              type:'select',
              slot:true,
              props:{
                label:'name',
                value:'id'
              },
              rules: [{
                message: "选择产品大类",
                required: true,
                trigger: 'blur'
              }],
              dicUrl: `/api/data-drawing-number-application/drawingnumberapplication/getChildNodeByParentId?parentId={{productParentId}}`,
              search: true,
            },
            {
              label: '图纸类别',
              type: 'tree',
              prop: 'drawingCategory',
              span: 8,
              props: {
                label: "name",
                value: "id"
              },
              search:true,
              dicUrl: "/api/data-category/drawingcategory/getDrawingCateGoryList",
              rules: [{
                message:'请选择图纸类别',
                required: true,
                trigger: 'blur'
              }]
            },
            {
              label: '申请数量',
              prop: 'num',
              span: 8,
              rules: [{
                message: "请输入申请数量",
                required: true,
                trigger: "blur",
                validator:validateNum,
              }]

            },
            {
              label: "备注",
              prop: 'remark'
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.drawingnumberapplication_add, false),
          viewBtn: this.vaildData(this.permission.drawingnumberapplication_view, false),
          delBtn: this.vaildData(this.permission.drawingnumberapplication_delete, false),
          editBtn: this.vaildData(this.permission.drawingnumberapplication_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      this.getLoginInfo();
    },
    methods: {
      // 查看按钮事件
      viewBtnFun(row){
        let id = row.id;
        this.tableData = [];
        this.loading = true;
        getApplicationDetailList(id).then(res => {
          let arry = res.data.data;
          let counter = 0;
          getDictionary({code: 'DNUS'}).then(res => {
              arry.forEach(tabl => {
              tabl.status = findByvalue(res.data.data,tabl.status);
              counter ++;
              if(counter === arry.length){
                this.tableData = arry;
                this.viewBox = true;
                this.loading = false;
              }
            });
          });
        });
      },
      
      // 导出excel中得数据
      exportExcel(){
        this.$confirm("是否导出图号申领得数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let url = `/api/data-drawing-number-application/drawingnumberapplication/export-drawing-number-application?${this.website.tokenHeader}=${getToken()}`;
          if (this.search.applicationTime!=null && this.search.applicationTime.size > 0 && typeof(this.search.applicationTime) != "undefined") {
            url += `&applicationTime_datege=`+this.search.applicationTime[0];
            url += `&applicationTime_datelt=`+this.search.applicationTime[1];
          }
          if (this.search.productParentId.length >0) {
            url += "&productParentId="+this.search.productParentId;
          }
          if (this.search.productChildId.length >0) {
            url += "&productChildId="+this.search.productChildId;
          }
          if (this.search.drawingCategory.length >0) {
            url += "&drawingCategory="+this.search.drawingCategory;
          }
          window.open(url);
        });
      },

      // 自定义编辑按钮
      handleEditBtn(row){
        this.editBox = true;
        getDetail(row.id).then(res => {
          this.editFormApplication = res.data.data;
        });
      },
      handleAdd(){
        this.getLoginInfo();
        this.addBox = true;
      },
      // 新增模态窗口的提交时间
      addDrawingApplication(){
        let form =  this.$refs.form.form;
        form.id = '';
        add(form).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.addBox = false;
          this.formApplication = '';
        });
      },
      getLoginInfo(){
        getLoginUserInfo().then((res) => {
          this.formApplication = res.data.data;
          this.formApplication.applicationTime = this.getNowFormatDate();
        });
      },
      getNowFormatDate(){ //获取当前时间

        let date = new Date();

        let seperator1 = "-"; //年月日之间的分隔

        let seperator2 = ":"; //时分秒之间的分隔

        let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; //获取月,如果小于10,前面补个0

        let strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); //获取日,如果小于10,前面补个0

        let strHours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); //获取小时,如果小于10,前面补个0

        let strMinutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); //获取分,如果小于10,前面补个0

        let strSeconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //获取秒,如果小于10,前面补个0

        let currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + strHours + seperator2 + strMinutes + seperator2 + strSeconds; //拼接一下

        return currentdate; //返回

      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        const {applicationTime} = params;
        let values = {
          ...params,
        };
        if (applicationTime) {
          values = {
            ...params,
            applicationTime_datege:applicationTime[0],
            applicationTime_datelt:applicationTime[1],
          };
          values.applicationTime = null;
          this.query.applicationTime = null;
        }
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(values, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
